import React, { useState, useRef, useEffect } from 'react'
import { cn } from '../../utils/cn'

interface DropdownMenuItem {
  icon?: React.ReactNode
  label: string
  href?: string
  onClick?: () => void
  type?: 'item' | 'separator'
  disabled?: boolean
}

interface DropdownMenuProps {
  trigger: React.ReactNode
  items: DropdownMenuItem[]
  align?: 'start' | 'end'
  className?: string
}

export function DropdownMenu({ trigger, items, align = 'start', className }: DropdownMenuProps) {
  const [isOpen, setIsOpen] = useState(false)
  const dropdownRef = useRef<HTMLDivElement>(null)
  const triggerRef = useRef<HTMLButtonElement>(null)

  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsOpen(false)
      }
    }

    if (isOpen) {
      document.addEventListener('mousedown', handleClickOutside)
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside)
    }
  }, [isOpen])

  const handleItemClick = (item: DropdownMenuItem) => {
    if (item.disabled) return
    
    if (item.onClick) {
      item.onClick()
    } else if (item.href) {
      window.location.href = item.href
    }
    
    setIsOpen(false)
  }

  return (
    <div className="relative inline-block text-left" ref={dropdownRef}>
      <button
        ref={triggerRef}
        onClick={() => setIsOpen(!isOpen)}
        className="focus:outline-none"
      >
        {trigger}
      </button>

      {isOpen && (
        <div className={cn(
          "absolute z-50 mt-2 w-56 rounded-md bg-white shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none",
          align === 'end' ? 'right-0' : 'left-0',
          className
        )}>
          <div className="py-1">
            {items.map((item, index) => {
              if (item.type === 'separator') {
                return (
                  <div key={index} className="h-px bg-gray-100 my-1" />
                )
              }

              return (
                <button
                  key={index}
                  onClick={() => handleItemClick(item)}
                  disabled={item.disabled}
                  className={cn(
                    "flex items-center w-full px-4 py-2 text-sm text-left hover:bg-gray-50 transition-colors",
                    item.disabled 
                      ? "text-gray-400 cursor-not-allowed" 
                      : "text-gray-700 hover:text-gray-900"
                  )}
                >
                  {item.icon && (
                    <span className="mr-3 flex-shrink-0">
                      {item.icon}
                    </span>
                  )}
                  {item.label}
                </button>
              )
            })}
          </div>
        </div>
      )}
    </div>
  )
}